<template>
  <div>
    <SupInput
      :InpList="InpList"
      :BtnList="BtnList"
      @clickFn="addFindFn"
    ></SupInput>
    <el-dialog
      :title="dialogtype == '1' ? '新增' : '编辑'"
      :visible.sync="dialogFormVisible"
    >
      <el-form :model="form">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item
            label="团购名称"
            prop="goodsName"
            v-if="dialogtype == 1"
          >
            <el-input v-model="ruleForm.goodsName"></el-input>
          </el-form-item>
          <el-form-item label="结束时间" prop="expireTime">
            <div class="block">
              <el-date-picker
                v-model="ruleForm.expireTime"
                type="datetime"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="优惠金额" prop="discount">
            <el-input v-model="ruleForm.discount"></el-input>
          </el-form-item>
          <el-form-item label="要求人数" prop="discountMember">
            <el-input v-model="ruleForm.discountMember"></el-input>
          </el-form-item>
          <el-form-item label="图片" v-if="dialogtype == 1">
            <el-upload
              class="avatar-uploader"
              action="https://www.shequlianshang.com/test/admin/storage/create"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >确认</el-button
            >
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-form>
    </el-dialog>
    <Suptable
      :headerData="headerData"
      :tableData="tableData"
      :isImg="true"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
      :current-page="pagenum"
      :total="total"
      :pagesizeList="fenye"
      :pagesize="pagesize"
    >
      <template v-slot:imgSlot="{ row }">
        <div>
          <img :src="row.row.picUrl" alt="" width="100" height="50" />
        </div>
      </template>
      <template v-slot:opera="{ row }">
        <div>
          <el-button
            type="text"
            @click="goEdit('2', row.row.goodsId, row.row)"
            size="small"
            >编辑</el-button
          >
          <el-button type="text" @click="godelete(row.row.goodsId)" size="small"
            >删除</el-button
          >
        </div>
      </template>
    </Suptable>
  </div>
</template>
<script>
import {
  bulkList,
  detBulk,
  addBulk,
  editBulk,
  queryBulk,
} from "@/api/bulkMock.js";
import Suptable from "@/components/Suptable";
import SupInput from "@/components/SupInput";
export default {
  name: "bulk",
  data() {
      let validatorcount =(rlue , value  , callback)=>{
          let myreg = /^(\d|[1-9]\d+)(\.\d+)?$/;
          if(!myreg.test(value) && value.trim()!=""){
              callback(new Error("请输入正确金额"))
          }else{
              callback()
          }
      }
      let validatormember =(rlue , value  , callback)=>{
          let myreg = /^[0-9]*[1-9][0-9]*$/;
          if(!myreg.test(value) && value.trim()!=""){
              callback(new Error("请输入正确人数"))
          }else{
              callback()
          }
      }
    return {
      title: true,
      imageUrl: "",
      ruleForm: {
        goodsId: "",
        goodsName: "",
        expireTime: "",
        discount: "",
        discountMember: "",
        picUrl: "",
      },
      rules: {
        goodsName: [
          { required: true,trigger: "blur" ,message:"请输入名称"},
        ],
        discount: [
          { required: true,  trigger: "blur", validator:validatorcount},
        ],
        discountMember: [
          { required: true,trigger: "blur" ,validator:validatormember},
        ],
      },
      dialogFormVisible: false,
      form: {
        name: "",
      },
      formLabelWidth: "120px",
      pagenum: 1,
      total: 0,
      pagesize: 5,
      fenye: [5, 10, 15, 20],
      dialogVisible: false,
      dialogtype: 1,
      tableData: [],
      InpList: [
        {
          model: "",
          text: "请输入商品名称",
        },
      ],
      BtnList: [
        {
          icon: "el-icon-search",
          name: "查找",
        },
        {
          icon: "el-icon-edit",
          name: "添加",
        },
      ],
      headerData: [
        {
          prop: "goodsId",
          label: "商品ID",
          width: "200",
        },
        {
          prop: "goodsName",
          label: "名称",
          width: "400",
        },

        {
          prop: "discount",
          label: "团购优惠",
          width: "100",
        },
        {
          prop: "discountMember",
          label: "团购要求",
          width: "200",
        },
        {
          prop: "addTime",
          label: "开始时间",
          width: "200",
        },
        {
          prop: "expireTime",
          label: "结束时间",
          width: "200",
        },
      ],
    };
    
  },
  mounted() {
    let _self = this;
    _self.userList();
  },
  methods: {
    submitForm(formName) {
      let _self = this;
      _self.dialogFormVisible = false;
      if (_self.dialogtype == 1) {
        _self.$refs[formName].validate((valid) => {
          let { goodsName, expireTime, discount, discountMember } =
            _self.ruleForm;
          let data = {
            goodsName,
            expireTime,
            discount,
            discountMember,
            picUrl: _self.imageUrl,
          };
          if (valid) {
            addBulk(data).then((res) => {
              if (res.meta.status == 200) {
                _self.$refs[formName].resetFields();
                _self.imageUrl = "";
                _self.value1 = "";
                _self.userList();
              } else {
                _self.$message({
                  type: "info",
                  message: "res.meta.msg",
                });
              }
            });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      } else {
          let _self = this;
          let { goodsId } = _self.ruleForm;
          let data = {
            goodsId,
            expireTime: _self.ruleForm.expireTime,
            discount: _self.ruleForm.discount,
            discountMember: _self.ruleForm.discountMember,
          };
          editBulk(data).then((res) => {
            // console.log(res);
            if (res.meta.status == 200) {
               _self.$refs[formName].resetFields();
              _self.userList();
            }
          });
    
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    handleSizeChange(val) {
      let _self = this;
      _self.pagesize = val;
      _self.userList();
    },
    handleCurrentChange(val) {
      let _self = this;
      _self.pagenum = val;
      _self.userList();
    },
    addFindFn(index) {
      let _self = this;
      _self.dialogtype = 1;
      if (index == 1) {
        _self.dialogFormVisible = true;
        _self.ruleForm = {};
      } else if (index == 0) {
        let data = {
          goodsId: _self.InpList[0].model,
        };
        queryBulk(data).then((res) => {
          // console.log(res);
          _self.tableData = [];
          if (res.meta.status == 200) {
            for (let item of res.data.arr) {
              let userData = {
                goodsId: item.goodsId,
                goodsName: item.goodsName,
                picUrl: item.picUrl,
                discount: item.discount,
                discountMember: item.discountMember,
                addTime: item.addTime,
                expireTime: item.expireTime,
              };
              _self.tableData.push(userData);
            }
            // _self.tableData = res.data.arr;
          } else {
            _self.userList();
          }
        });
      }
    },
    goEdit(type, goodsId, row) {
      let _self = this;
      _self.dialogtype = 2;
      _self.dialogFormVisible = true;
      _self.ruleForm = {
        goodsId: row.goodsId,
        expireTime: row.expireTime,
        discount: row.discount,
        discountMember: row.discountMember,
      };
    },
    godelete(goodsId) {
      let _self = this;
      _self
        .$confirm("确定删除吗", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          let data = { goodsId };
          detBulk(data).then((res) => {
            // console.log(res);
            if (res.meta.status == 200) {
              _self.$message({
                type: "success",
                message: "删除成功",
              });
              _self.userList();
            } else {
              _self.$message({
                type: "info",
                message: "res.meta.msg",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    userList() {
      let _self = this;
      let data = {
        pagenum: _self.pagenum,
        pagesize: _self.pagesize,
      };
      bulkList(data).then((res) => {
        // console.log(res);
        let _self = this;
        if (res.meta.status == 200) {
          _self.tableData = [];
          for (let item of res.data.user) {
            let userData = {
              goodsId: item.goodsId,
              goodsName: item.goodsName,
              picUrl: item.picUrl,
              discount: item.discount,
              discountMember: item.discountMember,
              addTime: item.addTime,
              expireTime: item.expireTime,
            };
            _self.tableData.push(userData);
          }
          _self.total = res.data.total;
          // _self.pagenum = res.data.pagenum
        }
      });
    },
  },
  components: { Suptable, SupInput },
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>